<template>
   <!--物资列表-详情列表-修改入库弹窗-表单-->
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row style="padding: 30px 0;">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="入库时间" prop="createTime">
              <j-date showTime date-format="YYYY-MM-DD HH:mm"  :disabled-date="disabledDate" :disabled-time="disabledDateTime" v-model="model.createTime"  style="width: 100%;"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="一级分类名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="categoryOneId"
            >
              <a-select
                :options="levelOneOptions"
                v-model="model.categoryOneId"
                placeholder="请输入一级分类名称"
                @change="changeLevelOne"
              >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="二级分类名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="categoryTwoId"
            >
              <a-select
                :options="levelTwoOptions"
                v-model="model.categoryTwoId"
                placeholder="请输入二级分类名称"
                @change="changeLevelTwo"
              >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="三级分类名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="categoryThreeId"
            >
              <a-select
                :options="levelThreeOptions"
                v-model="model.categoryThreeId"
                placeholder="请输入三级分类名称"
                @change="changeLevelThree"
              >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="送货单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="orderNo"
            >
              <a-input v-model="model.orderNo" placeholder="请输入订单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="供应商"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierId"
            >
              <a-select :options="supplierList" v-model="model.supplierId" placeholder="请输入供应商"></a-select>
            </a-form-model-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-model-item
              label="物资名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="platformProductId"
            >
              <a-select
                :options="StandardList"
                v-model="model.platformProductId"
                placeholder="请输入物资名称"
                @change="wzChange"
              ></a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="12" style="position: relative;">
            <span style="font-size: 12px; color: red; margin-left: 50px;top: -20px;position: absolute;">
              (如若型号要修改,请先点击其他物资名称,再点击要修改型号的物资名称)</span
            >
            <a-form-model-item
              label="型号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="model"
            >
              <a-select
                :options="modelData"
                v-model="model.model"
                placeholder="请输入型号"
              ></a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="number"
            >
              <a-input v-model="model.number" placeholder="请输入数量"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item
              label="性质"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="naturerange"
            >
              <a-select :options="naturerange" v-model="model.nature" placeholder="请选择存放方式">

              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item
              label="单价"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="price"
            >
              <a-input v-model="model.price" placeholder="请输入单价"></a-input>
            </a-form-model-item>
          </a-col>
          
        </a-row>
      </a-form-model>
    </j-form-container>

    <div></div>
  </a-spin>
</template>

<script>
  import moment from 'moment';
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDate from '@/components/jeecg/JDate'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { filterObj } from '@/utils/util'
import { httpAction, getAction, postAction } from '@/api/manage'
import JImageUpload from '@/components/jeecg/JImageUpload'
export default {
  name: 'WtMaterialsForm',
  mixins: [JVxeTableModelMixin, JeecgListMixin],
  components: {
    JFormContainer,
    JDate,
    JImageUpload,
  },
  data() {
    return {
      id: '',
      linkageConfig: [
        // 可配置多个联动
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      queryParam: {
        materialsId: this.id,
        queryEndTime: '',
        queryStartTime: '',
        warehouseName: '',
      },
      total2: {
        putTotal: '',
        outTotal: '',
      },
      naturerange: [
        {
          value: 1,
          label: '新入',
        },
        {
          value: 2,
          label: '借/还',
        },

        {
          value: 3,
          label: '租',
        },{
          value: 4,
          label: '调拨',
        },
      ],
      locationMode: [
        {
          value: 1,
          label: '露天',
        },
        {
          value: 2,
          label: '遮蔽',
        },
        {
          value: 3,
          label: '室内',
        },
        {
          value: 4,
          label: '顶棚',
        },
      ],

      model: {
        id: '',

        createTime: '',
        categoryOneId: '',
        categoryTwoId: '',
        categoryThreeId: '',
        supplierId: '',
        orderNo: '',
        platformProductId: '',
        isSupplyA: '',
        model: '',
        number: '',
        price: '',
        locationMode: '',
        nature: '',
        remark: '',
        // imgUrl:[]
      },

      levelOneOptions: [],
      levelTwoOptions: [],
      levelThreeOptions: [],
      treeData: [],
      StandardData: [],
      StandardList: [],
      BrandData: [],
      BrandList: [],
      locationMode: [],
      supplierData: [],
      supplierList: [],
      modelList: [],
      modelData: [],
      unitData: [],
      unitList: [],
      warehouseIdData: [],
      warehouseIdList: [],
      total1: [],
      refKeys: ['wtMaterialsDetail'],
      tableKeys: ['wtMaterialsDetail'],
      activeKey: 'wtMaterialsDetail',
      table1: {
        // 是否正在加载
        loading: false,
        // 分页器参数
        pagination: {
          // 当前页码
          current: 1,
          // 每页的条数
          pageSize: 200,
          // 可切换的条数
          pageSizeOptions: ['10', '20', '30', '100', '200'],
          // 数据总数（目前并不知道真实的总数，所以先填写0，在后台查出来后再赋值）
          total: 0,
        },
        // 最后选中的行
        lastRow: null,
        // 选择的行
        selectedRows: [],
        // 数据源，控制表格的数据
        dataSource: [],

        // 列配置，控制表格显示的列
        // linkageConfig: [
        //   { requestData: this.requestData, key: 'categoryOneId' },
        //   // 可配置多个联动
        // ],
      },
      treeData: [],
      treeData1: [],
      url: {
        list: '/materials/wtMaterials/detail/list',

        edit: '/materials/wtMaterials/updateEntrance',
        queryById: '/materials/wtMaterials/queryById',
        wtMaterialsDetail: {
          list: '/materials/wtMaterials/queryWtMaterialsDetailByMainId',
        },
      },
    }
  },
  isorter: {
    column: 'createTime',
    order: 'desc',
  },

  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    id: {
      type: String,
    },
  },
  computed: {},
  created() {
    this.loadTree1()
    this.loadTree()
  },
  mounted() {
    window.onbeforeunload = function (e) {
      var storage = window.localStorage
      storage.clear()
    }
  },
  methods: {
    moment,
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    },
    disabledDate(current) {
      console.log(1222,current)
      // Can not select days before today and today
      return current && current > moment().endOf('day');
    },
    disabledDateTime() {
      /* return {
        disabledHours: () => this.range(0, 24).splice(4, 20),
        disabledMinutes: () => this.range(30, 60),
        disabledSeconds: () => [55, 56],
      }; */
    },
    loadTree1() {
      var that = this
      getAction('/materials/wtWarehouse/getList').then((res) => {
        if (res.success) {
          that.warehouseIdData = []
          let warehouseList1 = res.result
          for (let a = 0; a < warehouseList1.length; a++) {
            let temp = supplierList1[a]
            temp.isLeaf = temp.leaf
            that.warehouseIdData.push(temp)
          }
          that.warehouseIdList = [...that.warehouseIdData].map((v) => {
            return {
              ...v,
              value: v.id,
              label: v.name,
            }
          })
          // console.log('fsd',this.supplierList);
        }
      })
      getAction('/wtCategory/list').then((res) => {
        if (res.success) {
          that.treeData1 = []
          var treeList = res.result
          for (let a = 0; a < treeList.length; a++) {
            let temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData1.push(temp)
          }

          that.levelOneOptions = [...that.treeData1].map((v) => {
            return {
              ...v,
              value: v.id,
              label: v.name,
            }
          })

          var list = []
          list = that.levelOneOptions.filter((item) => {
            if (item.id === that.model.categoryOneId) {
              return item.children
            }
          })
          if (list.length > 0) {
            that.levelTwoOptions = [...list[0].children].map((v) => {
              return {
                ...v,
                value: v.id,
                label: v.name,
              }
            })
          }
          var list2 = []
          list2 = that.levelTwoOptions.filter((item) => {
            if (item.id === that.model.categoryTwoId) {
              return item.children
            }
          })
          if (list2.length > 0) {
            that.levelThreeOptions = [...list2[0].children].map((v) => {
              return {
                ...v,
                value: v.id,
                label: v.name,
              }
            })
          }

          this.getList('categoryThreeId', that.model.categoryThreeId)
        }
      })
    },
    wzChange(evt) {
      // console.log('物质：', evt)
      // console.log('list:', this.StandardList)
      let list = []
      list = this.StandardList.filter((item) => {
        return item.id === evt
      })
      if (list.length > 0) {
        let str = list[0].model
        let listStr = []
        listStr = str.split(',')
        this.modelData = []

        listStr.forEach((item, index) => {
          this.modelData.push({
            value: item,
            label: item,
          })
        })
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },

    handleCancel() {
      this.close()
    },

    changeLevelOne() {
      this.clearForm()
      this.model.categoryTwoId = this.model.categoryThreeId = ''
      this.levelThreeOptions = []
      const item = this.treeData1.find((v) => v.id === this.model.categoryOneId)
      this.levelTwoOptions = (item.children || []).map((v) => {
        return {
          ...v,
          value: v.id,
          label: v.name,
        }
      })
      this.getList('categoryOneId', this.model.categoryOneId, this.model.model, this.model.unit)
    },
    changeLevelTwo() {
      this.clearForm()
      this.model.categoryThreeId = ''
      const levelOneItem = this.treeData1.find((v) => v.id === this.model.categoryOneId)
      const levelTwoItem = levelOneItem.children.find((v) => v.id === this.model.categoryTwoId) || []
      this.levelThreeOptions = (levelTwoItem.children || []).map((v) => {
        return {
          ...v,
          value: v.id,
          label: v.name,
        }
      })
      this.getList('categoryTwoId', this.model.categoryTwoId, this.model.unit)
    },
    changeLevelThree() {
      this.clearForm()
      this.getList('categoryThreeId', this.model.categoryThreeId)
    },
    handleCheckedCitiesChange() {
      this.StandardList.forEach((item) => {
        if (item.id === this.model.platformProductId) {
          this.modelList = item.model.split(',').map((v) => ({ value: v, label: v }))
          this.model.unit = item.unit
        }
      })
    },
    clearForm() {
      this.model.model = this.model.supplierId = this.model.platformProductId = ''
    },
    getList(category, id) {
      getAction('/wtSupplier/getListByCategory').then((res) => {
        if (res.success) {
          this.supplierData = []
          let supplierList1 = res.result
          for (let a = 0; a < supplierList1.length; a++) {
            let temp = supplierList1[a]
            temp.isLeaf = temp.leaf
            this.supplierData.push(temp)
          }
          this.supplierList = [...this.supplierData].map((v) => {
            return {
              ...v,
              value: v.id,
              label: v.name,
            }
          })
          // console.log('fsd',this.supplierList);
        }
      })

      getAction('/product/wtPlatformProduct/getListByCategory').then((res) => {
        if (res.success) {
          this.StandardData = []
          let StandardList1 = res.result

          for (let a = 0; a < StandardList1.length; a++) {
            let temp = StandardList1[a]
            temp.isLeaf = temp.leaf
            this.StandardData.push(temp)
          }

          this.StandardList = [...this.StandardData].map((v) => {
            return {
              ...v,
              value: v.id,
              label: v.name,
            }
          })
        }
      })

      getAction(`/wtBrand/getListByCategory?${category}=${id}`).then((res) => {
        if (res.success) {
          this.BrandData = []
          let BrandList1 = res.result
          for (let a = 0; a < BrandList1.length; a++) {
            let temp = BrandList1[a]
            temp.isLeaf = temp.leaf
            this.BrandData.push(temp)
          }
          this.BrandList = [...this.BrandData].map((v) => {
            return {
              ...v,

              value: v.id,
              label: v.name,
            }
          })
        }
      })
    },
    loadTree() {
      var that = this
      getAction(`/materials/wtMaterials/detail/list?MaterialsId=${this.id}`).then((res) => {
        if (res.success) {
          that.treeData = []
          var treeList = res.result.records
          for (let a = 0; a < treeList.length; a++) {
            let temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData.push(temp)
          }

          // that.model.id=that.treeData[0].id
        }
      })
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      // this.editAfter()
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})

      // 加载子表数据
      if (this.id) {
        let params = { id: this.id }
        this.requestSubTableData(this.url.wtMaterialsDetail.list, params, this.wtMaterialsDetailTable)
      }
    },

    validateError(msg) {
      this.$message.error(msg)
    },
    handleOk() {
      const that = this
      // console.log('提交接口--id：', that.model.id)
      // 触发表单验证

      that.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!that.model.id) {
            httpurl += that.url.add
            method = 'post'
          } else {
            httpurl += that.url.edit
            method = 'post'
          }
          // console.log('提交接口：', that.model)
          httpAction(httpurl, that.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>

<style scoped>
.count {
  width: 200px;
  height: 30px;
  /* background-color: #000; */
  margin-top: -40px;
}
.col1 {
  display: inline-block;
  width: 300px;
}
.col2 {
  display: inline-block;
  width: 55%;
  margin-left: -80px;
  margin-right: -100px;
}
</style>